package com.alnex.es.rest;

import org.apache.http.HttpHost;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Alnex
 * @CreateTime 2020-07-20 10:20
 * @Descirption rest 高级客户端
 */
public class TestHighESRest {

	private RestHighLevelClient client;

	@Before
	public void init() throws Exception {
		RestClientBuilder restClientBuilder =
				RestClient.builder(new HttpHost("192.168.200.128", 9200, "http"));

		this.client = new RestHighLevelClient(restClientBuilder);
	}

	@After
	public void after() throws Exception {
		this.client.close();
	}

	/**
	 * 新增文档 同步操作
	 */
	@Test
	public void testCreate() throws IOException {
		Map<String, Object> map = new HashMap<>();

		map.put("id", "2001");
		map.put("title", "陕西西安");
		map.put("price", "2001");

		IndexRequest indexRequest = new IndexRequest("haoke", "houst").source(map);

		IndexResponse indexResponse = this.client.index(indexRequest,
				RequestOptions.DEFAULT);

		System.out.println("id->" + indexResponse.getId());
		System.out.println("index->" + indexResponse.getIndex());
		System.out.println("type->" + indexResponse.getType());
		System.out.println("version->" + indexResponse.getVersion());
		System.out.println("result->" + indexResponse.getResult());
		System.out.println("shardInfo->" + indexResponse.getShardInfo());
	}

	/*
	 * 新增文档 异步操作
	 */
	@Test
	public void testcrerateAsync() throws InterruptedException {
		Map<String, Object> map = new HashMap<>();
		map.put("id", "2002");
		map.put("title", "帝都北京");
		map.put("price", "2002");

		IndexRequest indexRequest = new IndexRequest("haoke", "houst").source(map);

		this.client.indexAsync(indexRequest, RequestOptions.DEFAULT,
				new ActionListener<IndexResponse>() {

					@Override
					public void onResponse(IndexResponse indexResponse) {
						System.out.println("id->" + indexResponse.getId());
						System.out.println("index->" + indexResponse.getIndex());
						System.out.println("type->" + indexResponse.getType());
						System.out.println("version->" + indexResponse.getVersion());
						System.out.println("result->" + indexResponse.getResult());
						System.out.println("shardInfo->" + indexResponse.getShardInfo());
					}

					@Override
					public void onFailure(Exception e) {
						System.out.println(" 异步报错 " + e);
					}
				});

		Thread.sleep(2000);
	}

	/*
		查询数据
	 */
	@Test
	public void testQuery() throws IOException {
		GetRequest getRequest = new GetRequest("haoke", "houst",
				"AXNqHHe-algCgar5_bAC");

		// 指定返回的字段
		String[] inCludes = new String[]{"title", "id","price"};
		String[] exCludes = Strings.EMPTY_ARRAY;

		FetchSourceContext fetchSourceContext =
				new FetchSourceContext(true, inCludes, exCludes);
		getRequest.fetchSourceContext(fetchSourceContext);

		GetResponse response = this.client.get(getRequest, RequestOptions.DEFAULT);

		System.out.println("数据为 --> " + response.getSource());

	}

	/**
	 * 判断是否存在
	 */
	@Test
	public void testBooleanExists() throws IOException {
		GetRequest getRequest = new GetRequest("haoke", "houst",
				"AXNqHHealgCgar5bAC");
		// 不返回字段
		getRequest.fetchSourceContext(new FetchSourceContext(false));

		boolean exists = this.client.exists(getRequest, RequestOptions.DEFAULT);

		System.out.println(" 是否存在 " + exists);
	}

	/*
	 * 删除数据
	 */
	@Test
	public void testDelete() throws IOException {
		DeleteRequest deleteRequest =
				new DeleteRequest("haoke", "houst", "AXNqOlOHalgCgar5_bAF");

		DeleteResponse response = this.client.delete(deleteRequest, RequestOptions.DEFAULT);

		System.out.println("状态 = " + response.status()); //OK or NOT_FOUND

	}

	/**
		更新数据
	 */
	@Test
	public void testUpfdate() throws IOException {
		UpdateRequest updateRequest =
				new UpdateRequest("haoke", "houst", "AXNqE39ualgCgar5_bAA");

		Map<String, Object> map = new HashMap<>();
		map.put("title", "帝都北京");
		map.put("price", "2001");

		updateRequest.doc(map);

		UpdateResponse response =
				this.client.update(updateRequest, RequestOptions.DEFAULT);

		System.out.println(response.getVersion());
	}

	/**
	 * 测试搜索
	 */
	@Test
	public void testSearch() throws IOException {
		SearchRequest searchRequest = new SearchRequest("haoke");
		searchRequest.types("houst");

		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		// 条件数据查询 有问题
		// sourceBuilder.query(QueryBuilders.matchQuery("title","帝都北京"));
		sourceBuilder.from(0);
		sourceBuilder.size(5);
		sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

		// 请求条件添加
		searchRequest.source(sourceBuilder);

		SearchResponse search =
				this.client.search(searchRequest, RequestOptions.DEFAULT);

		System.out.println("搜索到 " + search.getHits().totalHits + " 条数据.");
		SearchHits hits = search.getHits();
		for (SearchHit hit : hits) {
			System.out.println(hit.getSourceAsString());
		}

	}
}
